import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/main.dart';
import 'package:zhaoxiaowu_app/utils/alert_utils.dart';
import 'package:zhaoxiaowu_app/utils/date_utils.dart';
import 'package:zhaoxiaowu_app/utils/event_bus.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';

class AccountingAddViewModel extends ChangeNotifier {
  List<Map> _types = [
    {"name": "收入", "id": 0},
    {"name": "支出", "id": 1},
  ];

  int _type = 0; // 类型选中下标
  List _modes = []; // 方式集合
  dynamic _mode; // 选中的方式对象

  String get modeText => mode == null ? "" : mode["name"];

  Map get typeMap => types[type];

  List get types => _types;

  int get type => _type;

  void setType(int newValue) {
    _type = newValue;
    notifyListeners();
  }

  List get modes => _modes;

  void setModes(List newValue) {
    _modes = newValue;
    notifyListeners();
  }

  dynamic get mode => _mode;

  void setMode(dynamic newValue) {
    _mode = newValue;
    notifyListeners();
  }

  void _getAccountingType(int action) async {
    var result = await Global.shared().get(
      "/zxw/AccountingType",
      parameters: {"action": action},
    );

    print(result.data);

    if (result.data["success"]) {
      _modes = result.data["data"];
      var value = await showObjectAlertDialog(_modes, "选择方式", "name");
      if (value != null && _mode != _modes[value]) {
        setMode(_modes[value]);
      }
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }

  void getModeAndAlert() async {
    if (_modes.length > 0) {
      var result = await showObjectAlertDialog(_modes, "选择方式", "name");
      if (result != null && _mode != _modes[result]) {
        setMode(_modes[result]);
      }
      return;
    }

    _getAccountingType(_types[_type]["id"]);
  }

  void insert(String money, String desc) async {
    if (_mode == null) {
      ToastUtils.showToast("方式没有选择");
      return;
    } else if (money.trim().isEmpty) {
      ToastUtils.showToast("金额没有填写");
      return;
    }

    ToastUtils.showActivity();

    Map map = {
      "t_id": _mode["id"],
      "u_id": Global.shared().user?.id,
      "action": _type,
      "money": money,
      "desc": desc,
      "date": getYMD(DateTime.now()),
    };

    var result = await Global.shared().put(
      "/zxw/AccountingHistory",
      parameters: {"json": jsonEncode(map)},
    );

    if (result.data["success"]) {
      ToastUtils.showSuccess("新增记账成功");
      setMode(null);
      setType(0);
      Future.delayed(
        Duration(seconds: 1),
        () {
          bus.emit("accouting_add_result");
          Navigator.of(navigatorKey.currentContext!).pop();
        },
      );
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }
}
